﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Diagnostics;
using System.Security.Policy;

namespace MailSend
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//禁用线程安全
            this.tabControl1.SelectedIndexChanged += new System.EventHandler(this.TabControl1_SelectedIndexChanged);//tabcontrol
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //读取文件到richtextbox
            FileStream fs = new FileStream(@".\mailsend.html", FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.UTF8);
            richTextBox1.Text = sr.ReadToEnd();
            sr.Close();//释放
            richTextBox2.ReadOnly = true;
        }

        private void button5_Click(object sender, EventArgs e)//button5=清空
        {
            richTextBox1.Text = "<html>\r\n<head>\r\n<meta charset=\"UTF-8\">\r\n</head>\r\n<body>\r\n\r\n</body>\r\n</html>";
            File.WriteAllText(@".\mailsend.html", richTextBox1.Text, System.Text.Encoding.UTF8);
            MessageBox.Show("已清空");
        }

        private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 获取当前选中的 TabPage  
            TabPage selectedTab = this.tabControl1.SelectedTab;

            // 根据选中的标签页执行不同的操作  
            if (selectedTab == this.tabPage1)
            {
                // 当 tabPage1 被选中时执行的代码  
                File.WriteAllText(@".\mailsend.html", richTextBox1.Text, System.Text.Encoding.UTF8);
                webBrowser1.Navigate(Application.StartupPath + @".\mailsend.html");
            }

        }

        private void button4_Click(object sender, EventArgs e)
        {
            File.WriteAllText(@".\mailsend.html", richTextBox1.Text, System.Text.Encoding.UTF8);
            MessageBox.Show("已保存");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("请输入收件人名称");
                return;
            }
            if (textBox2.Text == "")
            {
                MessageBox.Show("请输入主题");
                return;
            }
            if (textBox3.Text == "")
            {
                MessageBox.Show("请输入回信地址");
                return;
            }
            richTextBox2.Clear();
            tabControl1.SelectedTab = tabPage3;

            Task.Run(() =>
            {
                try
                {
                    using (StreamReader reader = new StreamReader(@".\Maddressee.txt"))
                    {
                        
                        string Maddressee;
                        while ((Maddressee = reader.ReadLine()) != null)
                        {
                            Task.Delay(15000).Wait();
                            //随机字符
                            FileStream fs = new FileStream(@".\randomtxt.txt", FileMode.Open, FileAccess.Read);
                            StreamReader sr = new StreamReader(fs, Encoding.UTF8);
                            string randomtxtread = sr.ReadToEnd().ToString();
                            sr.Close();//释放
                            string characters = randomtxtread;
                            Random randomtxt = new Random();
                            StringBuilder result = new StringBuilder(1000);

                            for (int i = 0; i < 1000; i++)
                            {
                                result.Append(characters[randomtxt.Next(characters.Length)]);
                            }
                            string rantxt = result.ToString();//rantxt=随机字符串

                            //随机字符结束


                            // 随机发件人开始  

                            string[] Msenderlines = File.ReadAllLines(@".\Msender.txt");


                            // 创建一个随机数生成器  
                            Random random = new Random();

                            // 获取一个随机索引  
                            int randomIndex = random.Next(Msenderlines.Length);

                            string Msender = Msenderlines[randomIndex];
                            // 随机发件人结束

                            // 指定你想要用来拆分的符号  
                            char[] separators = new char[] { ',', '，'};

                            // 使用Split方法拆分数据  
                            string[] MsenderOpen = Msender.Split(separators);

                            // 输出拆分后的结果  
                            string MsenderName = MsenderOpen[0];
                            string MsenderPwd = MsenderOpen[1];
                            string MsenderHost = MsenderOpen[2];

                            // 创建SmtpClient实例  
                            SmtpClient smtpClient = new SmtpClient
                            {
                                Host = MsenderHost, // 替换为你的SMTP服务器地址  
                                Port = 25, // 替换为你的SMTP服务器端口，通常是25, 465, 或 587  
                                EnableSsl = false, // 如果你的SMTP服务器需要SSL，设置为true  
                                DeliveryMethod = SmtpDeliveryMethod.Network,
                                UseDefaultCredentials = false,
                                Credentials = new NetworkCredential(MsenderName, MsenderPwd), // 替换为你的邮箱地址和密码  
                                Timeout = 20000,
                            };

                            // 创建MailMessage实例  
                            MailMessage mailMessage = new MailMessage
                            {
                                From = new MailAddress(MsenderName, textBox1.Text), // 替换为你的邮箱地址和名称  
                                Subject = textBox2.Text,
                                Body = richTextBox1.Text + "<div style='display:none'>" + rantxt + "</div>",
                                IsBodyHtml = true, // 设置邮件体为HTML格式  
                                Priority = MailPriority.High,

                        };

                            // 添加收件人  
                            mailMessage.To.Add(Maddressee); // 替换为收件人的邮箱地址
                            mailMessage.ReplyToList.Add(textBox3.Text);  

                            try
                            {
                                // 发送邮件  
                                smtpClient.Send(mailMessage);
                                DateTime currentTime = DateTime.Now;
                                richTextBox2.AppendText("\r\n" + currentTime.ToString("u") + "邮件发送成功！" + "收件人：" + Maddressee + "发件人：" + MsenderName);
                                //label1.Text = currentTime + "邮件发送成功！" + "收件人" + Maddressee + "发件人" + Msender;
                                File.AppendAllText("log.txt", "\r\n" + currentTime.ToString("u") + "邮件发送成功！" + "收件人：" + Maddressee + "发件人：" + MsenderName);
                                //MessageBox.Show("邮件发送成功！");
                            }
                            catch (Exception ex)
                            {
                                DateTime currentTime = DateTime.Now;
                                //MessageBox.Show("邮件发送失败: " + ex.Message);
                                richTextBox2.AppendText("\r\n" + currentTime.ToString("u") + "邮件发送失败！" + ex + "收件人：" + Maddressee + "发件人：" + MsenderName);
                                File.AppendAllText("log.txt", "\r\n" + currentTime.ToString("u") + "邮件发送失败！" + ex + "收件人：" + Maddressee + "发件人：" + MsenderName);
                            }
                        }
                        DateTime currentTimeov = DateTime.Now;
                        richTextBox2.AppendText("\r\n" + currentTimeov.ToString("u") + "邮件发送结束！" );

                    }
                }
                catch (Exception ex)
                {
                    // 处理任何异常，例如文件不存在或无法读取  
                    DateTime currentTime = DateTime.Now;
                    //MessageBox.Show("邮件发送失败: " + ex.Message);
                    richTextBox2.AppendText("\r\n" + currentTime.ToString("u") + "无法读取文件" + ex);
                    File.AppendAllText("log.txt", "\r\n" + currentTime.ToString("u") + "无法读取文件" + ex);
                    //MessageBox.Show("无法读取文件: " + ex.Message);

                }
            });

        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("注意：格式为  发件箱,密码,SMTP服务器  中间以英文,隔开，每行一条");
            System.Diagnostics.Process.Start(@".\Msender.txt");

        }

        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("注意：格式为 每行一条");
            System.Diagnostics.Process.Start(@".\Maddressee.txt");
        }

        private void button6_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(@".\log.txt");
        }

        private void button7_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(@".\randomtxt.txt");
        }

        private void label1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://gitee.com/suluotech/email-group-sender");

        }
    }
}
